//
//  ProfileSettingViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-27.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ProfileSettingViewController.h"
#import "NetworkAccessManager.h"
//#import <UIImageView+AFNetworking.h>
//#import <UIImageView+WebCache.h>
#import "SNSCropImageViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"
#import "ChildInfo.h"
//#import <UIImageView+WebCache.h>
#import "CopyLabel.h"

#define kCropPhotoViewId    @"cropPhoto"
#define kCropPhotoSize      180

@interface ProfileSettingViewController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>{
    
    NSOperationQueue *operationQueue;
    
    UIActionSheet *photoActionSheet;
    UIActionSheet *copyChildCodeActionSheet;
}
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UILabel *nameTextField;
@property (weak, nonatomic) IBOutlet UILabel *childCodeLabel;
@property (weak, nonatomic) IBOutlet UILabel *childCodeTitle;

@end

@implementation ProfileSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [_nameTextField setText:self.appDelegate.user[@"name"]];
    
    CALayer *layer = [_photoView layer];
    layer.borderColor = [[UIColor whiteColor] CGColor];
    layer.borderWidth = 2.0f;
    _photoView.image = self.appDelegate.userPhoto;
//    [_photoView setImage self.appDelegate.userPhoto];
    //    [_photoView setImage:[UIImage imageNamed:@"imageUserPhotoDefault"]];
    
    //    operationQueue = [[NSOperationQueue alloc] init];
    //    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:nil];
    //    [operationQueue addOperation:op];
    
    if (self.appDelegate.userType == UserTypeParent) {
        [self loadRemoteData];
    }else{
        [self.childCodeTitle setHidden:YES];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadImage{
    NSURL *photoUrl = [NSURL URLWithString:self.appDelegate.user[@"photo"]];
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photoUrl]];
    [_photoView setImage:image];
}

-(void)loadRemoteData{
    NSString *uriString = [NSString stringWithFormat:@"Child/%@.json", self.appDelegate.user[@"childId"]];
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            ChildInfo *child = [[ChildInfo alloc]initWithDictionary:responseObject[@"data"]];
            self.childCodeLabel.text = child.authenticationCode;
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}

- (IBAction)changePhotoAction:(id)sender {
    NSLog(@"selectPhotoAction");
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"拍照", nil);
        NSString *otherButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        photoActionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitle, nil];
    }else{
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        photoActionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:nil, nil];
    }
    [photoActionSheet showInView:self.view];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"button index %zd", buttonIndex);
    if (actionSheet == photoActionSheet) {
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            if (buttonIndex == 0) {
                // 拍照
                
                UIImagePickerController *picker = [[UIImagePickerController alloc]init];
                picker.delegate =self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
            }else if (buttonIndex == 1){
                // 从相册中选取
                UIImagePickerController *picker = [[UIImagePickerController alloc]init];
                picker.delegate =self;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }else{
            if (buttonIndex == 0) {
                // 从相册中选取
                UIImagePickerController *picker = [[UIImagePickerController alloc]init];
                picker.delegate =self;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }
        
    }else if (actionSheet == copyChildCodeActionSheet){
        
    }
    
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"pick a photo");
    //    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    
    [picker dismissViewControllerAnimated:NO completion:^{
        NSLog(@"dismissViewControllerAnimated imagePicker");
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            UIImage *preview = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
            
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil cropRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
            
            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            imageEditor.previewImage = preview;
            imageEditor.noOptionButton = YES;
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    UIImage *photo = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    [self uploadTeacherPhoto:photo];
                }
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        } failureBlock:^(NSError *error) {
            NSLog(@"error occour when read preview photo %@", error);
            
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil cropRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            //            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    UIImage *photo = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    
                    [self uploadTeacherPhoto:photo];
                }
                
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        }];
        
        
    }];
    
}

- (void)uploadTeacherPhoto:(UIImage *)photo{
    NSString *uriString = @"Account/0/changePhoto.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]POST:uriString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(photo, 1.0);
        [formData appendPartWithFileData:data name:@"photo" fileName:[NSString stringWithFormat:@"%@.jpg",[[NSProcessInfo processInfo] globallyUniqueString]] mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"upload photo result is %@", responseObject);
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            _photoView.image = photo;
            self.appDelegate.userPhoto = photo;
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"upload photo error is %@\nopernation %@",error, operation);
        [UIAlertView alertWithNetworkError];
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
